package com.example.adminbase.service;

import com.example.adminbase.dao.CrudDao;
import com.example.adminbase.util.Assert;

import java.io.Serializable;
import java.util.List;

public interface CrudService<PK extends Serializable, T> {
    default T findById(PK id) {
        Assert.notNull(id, "查询的id不能为空");
        return getDao().findById(id);
    }
    default List<T> findAll() {
        return getDao().findAll();
    }

    //todo: 在保存成功后发布事件
    default void save(T record) {
        boolean continued = beforeSave(record);
        if(continued) {
            getDao().insertSelective(record);
        }
    }

   default boolean beforeSave(T record) {
        return true;
   }

    default void update(T record) {
        boolean continued = beforeUpdate(record);
        if(continued) {
            getDao().update(record);
        }
    }

    default void updateSelective(T record) {
        boolean continued = beforeUpdate(record);
        if(continued) {
            getDao().updateSelective(record);
        }
    }

    default boolean beforeUpdate(T record) {
        return true;
    }

    default void delete(PK id) {
        Assert.notNull(id, "删除的id不能为空");
        getDao().delete(id);
    }

    default void deleteWithIds(List<PK> ids) {
        Assert.notNull(ids, "删除的id不能为空");
        getDao().deleteWithIds(ids);
    }

    CrudDao<PK, T> getDao();
}
